package com.cems.controller;

import com.cems.pojo.ComUser;
import com.cems.pojo.SysUser;
import com.cems.service.UserService;
import com.cems.util.RedisGeoUtil;
import com.cems.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @ClassName JWController
 * @Author 陈新予(blank)
 * @Date 2021/5/22
 * @Version 1.0
 */
@Controller
public class JWController {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    RedisGeoUtil redisGeoUtil;
    @Autowired
    UserService userService;

    @GetMapping("JWset/{id}")
    public String JWset(@PathVariable String id, Model model, HttpSession session) {
        //redis查数据
        SysUser user = (SysUser) session.getAttribute("user");
        //获取用户id
        Integer userId = user.getId();
        //redis中key的名字
        String redisKey = "cems_JW";
        //查询值
        String JWinfo = String.valueOf(redisUtil.get("cems_jw_info_" + userId));
        List<Point> points = redisGeoUtil.geoGet(redisKey, String.valueOf(userId));
        System.out.println("=========info" + JWinfo);
        if (JWinfo == null || JWinfo.equals("null")) {
            JWinfo = "未设置";
        }
        try {
            model.addAttribute("jing", points.get(0).getX());
            model.addAttribute("wei", points.get(0).getY());
        } catch (NullPointerException e) {
            model.addAttribute("jing", "未设置");
            model.addAttribute("wei", "未设置");
        }
        model.addAttribute("info", JWinfo);
        return "User/JingWeiSet";
    }

    @GetMapping("getJWmap")
    public String GetJWmap() {
        return "User/GetJWmap";
    }

    @GetMapping("setRedisUserJW")
    @ResponseBody
    public int setUserJW(String jing, String wei, String info, HttpSession session) {
        try {
            SysUser user = (SysUser) session.getAttribute("user");
            //获取用户id
            Integer userId = user.getId();
            //redis中key的名字
            String redisKey = "cems_JW";
            //存入redis
            Long addnum = redisGeoUtil.geoAdd(redisKey, new Point(Double.valueOf(jing), Double.valueOf(wei)), String.valueOf(userId));
            //设置详细地址
            redisUtil.set("cems_jw_info_" + userId, info);
            //读取redis
            List<Point> points = redisGeoUtil.geoGet(redisKey, String.valueOf(userId));
            //成功则输出
            System.out.println("添加位置坐标点：" + userId + points);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("失败了");
            return 0;
        }
    }

    @GetMapping("tonearpeople")
    public String toNearPeople(HttpSession session, Model model) {
        SysUser user;
        Integer userId;
        //redis中key的名字
        String redisKey = "cems_JW";
        try {
            user = (SysUser) session.getAttribute("user");
            userId = user.getId();
        } catch (Exception e) {
            return "User/userlogin";
        }
        try {
            List<Point> points = redisGeoUtil.geoGet(redisKey, String.valueOf(userId));
            //添加自己的位置
            model.addAttribute("userPX", points.get(0).getX());
            model.addAttribute("userPY", points.get(0).getY());
            String JWinfo = String.valueOf(redisUtil.get("cems_jw_info_" + userId));
            if (JWinfo == null || JWinfo.equals("null")) {
                JWinfo = "未知地点";
            }
            //添加自己的未知
            model.addAttribute("info", JWinfo);
            //查询其他的点
            List<String> xlist = new ArrayList<>();//经度
            List<String> ylist = new ArrayList<>();//纬度
            List<String> namelist = new ArrayList<>();//昵称
            List<String> infolist = new ArrayList<>();//详细信息
            Set<Object> allPeoples = redisUtil.zRange(redisKey, 0, -1);
            //循环拿取其他点的信息
            for (Object allPeople : allPeoples) {
                //跳过自己
                if (Objects.equals((Integer) allPeople, userId)) {
                    continue;
                }
                Integer otherId = (Integer) allPeople;
                //通过id查询点
                List<Point> otherPoint = redisGeoUtil.geoGet(redisKey, String.valueOf(otherId));
                xlist.add(String.valueOf(otherPoint.get(0).getX()));
                ylist.add(String.valueOf(otherPoint.get(0).getY()));
                namelist.add(userService.selOneUser(otherId).getUserPname());
                String oinfo = String.valueOf(redisUtil.get("cems_jw_info_" + otherId));
                if (oinfo == null || oinfo.equals("") || oinfo.equals("null")) {
                    oinfo = "该用户暂时没有设置详细信息哦~";
                }
                infolist.add(oinfo);
            }
            model.addAttribute("xlist", xlist);
            model.addAttribute("ylist", ylist);
            model.addAttribute("namelist", namelist);
            model.addAttribute("infolist", infolist);
            return "font/baiduMap/map";
        } catch (NullPointerException e) {
            //读取不到位置信息则跳转到设置位置的页面
            ComUser comUser = userService.selOneUser(userId);
            SysUser sysUser = userService.selOneSysUser(userId);
            model.addAttribute("comUser", comUser);
            model.addAttribute("sysUser", sysUser);
            return "font/baiduMap/err";
        }
    }

    @GetMapping("toNearPeopleInfo")
    public String toNearPeopleInfo(HttpSession session, Model model) {
        SysUser user;
        Integer userId;
        //redis中key的名字
        String redisKey = "cems_JW";
        try {
            user = (SysUser) session.getAttribute("user");
            userId = user.getId();
        } catch (Exception e) {
            return "User/userlogin";
        }
        //存储list
        List<String> namelist = new ArrayList<>();
        List<String> infolist = new ArrayList<>();
        List<String> mlsit = new ArrayList<>();
        //查询10KM以内的人
        try {
            //获取自己的位置
            String oinfo = String.valueOf(redisUtil.get("cems_jw_info_" + userId));
            System.out.println(oinfo);
            if (oinfo == null || oinfo.equals("null")) {
                return "font/baiduMap/err";
            }
            GeoResults<RedisGeoCommands.GeoLocation<String>> points = redisGeoUtil.nearByPlace(redisKey, String.valueOf(userId), new Distance(10, Metrics.KILOMETERS), 100);
            //遍历取得附近的人的id
            for (GeoResult<RedisGeoCommands.GeoLocation<String>> point : points) {
                String otherId = point.getContent().getName();
                if (otherId.equals(userId.toString())) {
                    continue;
                }
                System.out.println(point.getDistance().getValue() * 1000 + "---->user" + point.getContent().getName());
                mlsit.add(String.valueOf(point.getDistance().getValue() * 1000));
                ComUser comUser = userService.selOneUser(Integer.parseInt(otherId));
                namelist.add(comUser.getUserPname());
                infolist.add(comUser.getUserHouse());
            }
            if (namelist.size() == 0) {
                return "font/baiduMap/noPerple";
            }
            int pages;
            if (namelist.size() % 5 == 0) {
                pages = namelist.size() / 5;
            } else {
                pages = namelist.size() / 5 + 1;
            }
            model.addAttribute("namelist", namelist);
            model.addAttribute("infolist", infolist);
            model.addAttribute("mlsit", mlsit);
            model.addAttribute("pages", pages);
            return "font/baiduMap/nearPeople";
        } catch (Exception e) {
            return "font/baiduMap/err";
        }
    }
}
